import { ref, type Ref } from 'vue'
import type { PaginationParams } from '@/api/types'
import type { BulkOperationResponse } from '@/api/factories/createCrudApi'
import notify from '@/utils/notify'
import { logger } from '@/utils/logger'

/**
 * CRUD Store 工厂函数
 * 用于快速创建标准的增删改查Store逻辑，减少重复代码
 *
 * @template T - 实体类型
 * @template TCreate - 创建数据类型
 * @template TUpdate - 更新数据类型
 * @template TApi - API 对象类型
 *
 * @param api - API 对象（需包含标准CRUD方法）
 * @param options - 配置选项
 * @returns 包含标准CRUD状态和方法的对象
 *
 * @example
 * ```ts
 * export const useLeadStore = defineStore('lead', () => {
 *   const baseCrud = createCrudStore(leadApi, {
 *     entityName: '客户',
 *     entityNamePlural: '客户列表'
 *   })
 *
 *   // 添加自定义逻辑
 *   const rentLeads = computed(() =>
 *     baseCrud.items.value.filter(lead => lead.demand_type === 'rent_whole')
 *   )
 *
 *   return { ...baseCrud, rentLeads }
 * })
 * ```
 */
export function createCrudStore<
  T extends { id?: number },
  TCreate = Partial<T>,
  TUpdate = Partial<T>,
  TFilter extends Record<string, unknown> = Record<string, unknown>,
  TApi extends {
    getList: (params: PaginationParams & TFilter) => Promise<{ items: T[]; total: number }>
    getById: (id: number) => Promise<T>
    create: (data: TCreate) => Promise<T>
    update: (id: number, data: TUpdate) => Promise<T>
    delete: (id: number) => Promise<void>
    bulkDelete?: (ids: number[]) => Promise<BulkOperationResponse>
    restore?: (id: number) => Promise<T>
    bulkRestore?: (ids: number[]) => Promise<BulkOperationResponse>
    getDeletedList?: (params: PaginationParams & TFilter) => Promise<{ items: T[]; total: number }>
  } = never,
>(
  api: TApi,
  options: {
    /** 实体名称（如: "客户"） */
    entityName: string
    /** 实体复数名称（如: "客户列表"） */
    entityNamePlural?: string
  }
) {
  const { entityName, entityNamePlural = `${entityName}列表` } = options

  // ========== State ==========
  const items: Ref<T[]> = ref([])
  const currentItem: Ref<T | null> = ref(null)
  const total = ref(0)
  const loading = ref(false)

  // ========== Actions ==========

  /**
   * 获取列表
   */
  async function fetchList(params: PaginationParams & TFilter = { page: 1, page_size: 10 } as PaginationParams & TFilter) {
    loading.value = true
    try {
      const res = await api.getList(params)
      items.value = res.items
      total.value = res.total
      return res
    } catch (error) {
      logger.error(`获取${entityNamePlural}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`获取${entityNamePlural}失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取详情
   */
  async function fetchById(id: number) {
    loading.value = true
    try {
      const res = await api.getById(id)
      currentItem.value = res
      return res
    } catch (error) {
      logger.error(`获取${entityName}详情失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`获取${entityName}详情失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建
   */
  async function create(data: TCreate) {
    loading.value = true
    try {
      const res = await api.create(data)
      notify.success(`创建${entityName}成功`)
      return res
    } catch (error) {
      logger.error(`创建${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`创建${entityName}失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新
   */
  async function update(id: number, data: TUpdate) {
    loading.value = true
    try {
      const res = await api.update(id, data)
      notify.success(`更新${entityName}成功`)
      return res
    } catch (error) {
      logger.error(`更新${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`更新${entityName}失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除
   */
  async function deleteItem(id: number) {
    loading.value = true
    try {
      await api.delete(id)
      notify.success(`删除${entityName}成功`)
      return true
    } catch (error) {
      logger.error(`删除${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`删除${entityName}失败`)
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量删除（优化版：使用批量接口）
   */
  async function deleteMany(ids: number[]) {
    loading.value = true
    try {
      // ✅ P1-1修复: 使用批量删除API（1次请求）替代循环（N次请求）
      if (api.bulkDelete) {
        const result = await api.bulkDelete(ids)
        notify.success(result.message || `批量删除${entityName}成功`)
        return true
      }

      // 降级方案：如果API不支持批量删除，使用循环
      const promises = ids.map(id => api.delete(id))
      await Promise.all(promises)
      notify.success(`批量删除${entityName}成功`)
      return true
    } catch (error) {
      logger.error(`批量删除${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`批量删除${entityName}失败`)
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 恢复单个已删除记录
   */
  async function restoreItem(id: number) {
    if (!api.restore) {
      notify.error('该功能不支持恢复操作')
      return false
    }

    loading.value = true
    try {
      await api.restore(id)
      notify.success(`恢复${entityName}成功`)
      return true
    } catch (error) {
      logger.error(`恢复${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`恢复${entityName}失败`)
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量恢复已删除记录
   */
  async function restoreMany(ids: number[]) {
    if (!api.bulkRestore) {
      notify.error('该功能不支持批量恢复操作')
      return false
    }

    loading.value = true
    try {
      const result = await api.bulkRestore(ids)
      notify.success(result.message || `批量恢复${entityName}成功`)
      return true
    } catch (error) {
      logger.error(`批量恢复${entityName}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`批量恢复${entityName}失败`)
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取已删除记录列表
   */
  async function fetchDeletedList(params: PaginationParams & TFilter = { page: 1, page_size: 10 } as PaginationParams & TFilter) {
    if (!api.getDeletedList) {
      notify.error('该功能不支持查询已删除记录')
      return null
    }

    loading.value = true
    try {
      const res = await api.getDeletedList(params)
      items.value = res.items
      total.value = res.total
      return res
    } catch (error) {
      logger.error(`获取已删除${entityNamePlural}失败`, { error: error instanceof Error ? error.message : 'Unknown error' })
      notify.error(`获取已删除${entityNamePlural}失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    // State
    items,
    currentItem,
    total,
    loading,

    // Actions
    fetchList,
    fetchById,
    create,
    update,
    deleteItem,
    deleteMany,

    // ✅ P1-2, P1-3, P1-4修复: 新增恢复和已删除列表功能
    restoreItem,
    restoreMany,
    fetchDeletedList,
  }
}
